package com.zheng.upms.server.controller.manage;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.validator.LengthValidator;
import com.zheng.upms.common.constant.UpmsResult;
import com.zheng.upms.common.constant.UpmsResultConstant;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.dao.model.UpmsDictExample;
import com.zheng.upms.rpc.api.UpmsDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: UpmsDictController <br>
 * @Description: 数据字典管理控制类 <br>
 * @date 2018/9/11 10:39<br>
 **/
@Controller
@Api(value = "数据字典", description = "数据字典")
@RequestMapping("/manage/dict")
public class UpmsDictController extends BaseController{

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsDictController.class);

    @Autowired
    private UpmsDictService upmsDictService;

    @ApiOperation(value = "数据字典首页")
    @RequiresPermissions("upms:dict:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/dict/index.jsp";
    }

    @ApiOperation(value = "数据字典树列表")
    @RequiresPermissions("upms:dict:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        UpmsDictExample upmsDictExample = new UpmsDictExample();
        UpmsDictExample.Criteria criteria = upmsDictExample.createCriteria();
        //criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            upmsDictExample.setOrderByClause(sort + " " + order);
        }else{
            upmsDictExample.setOrderByClause(" dic_code,dic_value asc");
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andDicNameLike("%" + search + "%");
        }
        List<UpmsDict> rows = upmsDictService.selectByExampleForOffsetPage(upmsDictExample, offset, limit);
        long total = upmsDictService.countByExample(upmsDictExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增数据字典")
    @RequiresPermissions("upms:dict:create")
    @RequestMapping(value = "/create/{id}", method = {RequestMethod.GET})
    public String create(@PathVariable("id") int id, ModelMap modelMap) {
        if(StringUtils.isNotBlank(id+"")){
            UpmsDict UpmsDict = upmsDictService.selectByPrimaryKey(id);
            modelMap.put("pupmsdict", UpmsDict);
    }
        return "/manage/dict/create.jsp";
    }

    @ApiOperation(value = "新增数据字典")
    @RequiresPermissions("upms:dict:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public Object create(UpmsDict upmsDict) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsDict.getDicCode(), new LengthValidator(1, 50, "字典代码"))
                .on(upmsDict.getDicValue(), new LengthValidator(1, 50, "字典值"))
                .on(upmsDict.getDicName(), new LengthValidator(1, 50, "字典名称"))
                .on(upmsDict.getDicText(), new LengthValidator(0, 100, "字典描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        int count = upmsDictService.insertSelective(upmsDict);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除数据字典")
    @RequiresPermissions("upms:dict:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        int count = upmsDictService.deleteByPrimaryKeys(ids);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改数据字典")
    @RequiresPermissions("upms:dict:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsDict upmsDict = upmsDictService.selectByPrimaryKey(id);
        modelMap.put("upmsdict", upmsDict);
        return "/manage/dict/update.jsp";
    }

    @ApiOperation(value = "修改数据字典")
    @RequiresPermissions("upms:dict:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") int id, UpmsDict upmsDict) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsDict.getDicCode(), new LengthValidator(1, 50, "字典代码"))
                .on(upmsDict.getDicValue(), new LengthValidator(1, 50, "字典值"))
                .on(upmsDict.getDicName(), new LengthValidator(1, 50, "字典名称"))
                .on(upmsDict.getDicText(), new LengthValidator(0, 100, "字典描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        upmsDict.setId(id);
        int count = upmsDictService.updateByPrimaryKeySelective(upmsDict);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }
    @ApiOperation(value = "刷新数据字典缓存")
    @RequiresPermissions("upms:dict:cacherefresh")
    @RequestMapping(value = "/cacherefresh", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object cacherefresh() {
        int ret = upmsDictService.cacherefresh();
        return new UpmsResult(UpmsResultConstant.SUCCESS, ret);
    }
}
